package com.google.gwt.websockets.client;

public class WebSocket {
    private WebSocketCallback callback = null;

    /** Native handle. */
    private Object handle = null;

    public WebSocket(WebSocketCallback callback) {
        this.callback = callback;
    }

    public void connect(String server) {
        if (handle != null) close();

        handle = _connect(callback, server);
    }

    public void close() {
        if (handle == null) throw new IllegalStateException("Not connected");

        _close(handle);

        handle = null;
    }

    public void send(String data) {
        if (handle == null) throw new IllegalStateException("Not connected");

        _send(handle, data);
    }

    private native Object _connect(WebSocketCallback callback, String server) /*-{
        var ws = new WebSocket(server);

        ws.onopen = function() {
            callback.@com.google.gwt.websockets.client.WebSocketCallback::onConnect()();
        };

        ws.onmessage = function(response) {
            callback.@com.google.gwt.websockets.client.WebSocketCallback::onMessage(Ljava/lang/String;)(response.data);
        };

        ws.onclose = function() {
            callback.@com.google.gwt.websockets.client.WebSocketCallback::onDisconnect()();
        };

        return ws;
    }-*/;

    private native void _close(Object handle) /*-{
        handle.close();
    }-*/;

    private native void _send(Object handle, String data) /*-{
        handle.send(data);
    }-*/;

    public static native boolean isSupported() /*-{
        return !!window.WebSocket;
    }-*/;
}
